package com.activemq.config;

import java.util.Arrays;

import javax.jms.Queue;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.util.StringUtils;

import com.activemq.LogProducer;

@Configuration  
public class QueueConfig {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(QueueConfig.class);
	
	//@Value("${activemq.broker_url}")
	private String mqUrl;
	//@Value("${activemq.user}")
	private String mqName;
	//@Value("${activemq.password}")
	private String mqPassword;
	//@Value("${activemq.trustedPackages}")
	private String trustedPackages;
  
	@Bean
    public Queue queue() {
       return new ActiveMQQueue("sample.queue");
    }
   
    @Bean
    public Topic topic1() {
       return new ActiveMQTopic("sample.topic");
    }
    
    @Bean
    public ActiveMQConnectionFactory activeMQConnectionFactory() {
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(ActiveMqPropertiesConfig.broker_url);
        factory.setUserName(ActiveMqPropertiesConfig.user);
        factory.setPassword(ActiveMqPropertiesConfig.password);
        //factory.setClientID("11");
        
        if(!StringUtils.isEmpty(ActiveMqPropertiesConfig.trustedPackages)) {
        	factory.setTrustedPackages(Arrays.asList(ActiveMqPropertiesConfig.trustedPackages.split(",")));
        }
        factory.setTrustAllPackages(ActiveMqPropertiesConfig.trustAllPackages);
        
        return factory;
    }
    
    @Bean
    public JmsListenerContainerFactory<?> jmsListenerContainerTopic(ActiveMQConnectionFactory connectionFactory) {
        DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
        bean.setPubSubDomain(true);
        bean.setConnectionFactory(connectionFactory);
        return bean;
    }
    @Bean
    public JmsListenerContainerFactory<?> jmsListenerContainerQueue(ActiveMQConnectionFactory connectionFactory) {
        DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
        bean.setConnectionFactory(connectionFactory);
        return bean;
    }
    @Bean
    public JmsMessagingTemplate jmsMessagingTemplate(ActiveMQConnectionFactory connectionFactory){
        return new JmsMessagingTemplate(connectionFactory);
    }
} 
